package com.ztmao.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztmao.shortlink.admin.common.biz.user.UserContext;
import com.ztmao.shortlink.admin.common.constant.RedisCacheConstant;
import com.ztmao.shortlink.admin.convention.result.Result;
import com.ztmao.shortlink.admin.dao.entity.GroupDO;
import com.ztmao.shortlink.admin.dao.mapper.GroupMapper;
import com.ztmao.shortlink.admin.dto.req.ShortLinkGroupSortReqDTO;
import com.ztmao.shortlink.admin.dto.req.ShortLinkGroupUpdateReqDTO;
import com.ztmao.shortlink.admin.dto.resp.ShortLinkGroupRespDTO;
import com.ztmao.shortlink.admin.remote.ShortLinkActualRemoteService;
import com.ztmao.shortlink.admin.remote.resp.ShortLinkGroupCountQueryRespDTO;
import com.ztmao.shortlink.admin.service.GroupService;
import com.ztmao.shortlink.admin.util.RandomGenerator;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
/**
 * 短链接分组接口实现层
 */
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {
    //todo  远程服务调用
    private final ShortLinkActualRemoteService shortLinkRemoteService ;
    private final RedissonClient redissonClient;
    @Value("${short-link.group.max-num}")
    private Integer groupMaxNum;
    @Override
    public void save(String name) {
save(UserContext.getUsername(),name);
    }
    @Override
    public void save(String username,String name) {
        RLock lock = redissonClient.getLock(String.format(RedisCacheConstant.LOCK_GROUP_CREATE_KEY, username));
        lock.lock();
        try{
            LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getUsername, username)
                    .eq(GroupDO::getDelFlag, 0);
            List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
            if(CollUtil.isNotEmpty(groupDOList) && groupDOList.size() > groupMaxNum){
                throw new RuntimeException("分组数量已达到上限");
            }

            String gid ;
            do{
                gid = RandomGenerator.generateRandom();
            }while(hasGid(gid, username));
            GroupDO build = GroupDO.builder()
                    .gid(gid)
                    .username(username)
                    .name(name)
                    .build();
            baseMapper.insert(build);
        }finally {
            lock.unlock();
        }

    }



    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getDelFlag, 0)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .orderByDesc(GroupDO::getSortOrder, GroupDO::getUpdateTime);
        List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);

        List<ShortLinkGroupRespDTO> shortLinkGroupRespDTOS = BeanUtil.copyToList(groupDOList, ShortLinkGroupRespDTO.class);
        //远程调用获取gid对应的短链数量
        Result<List<ShortLinkGroupCountQueryRespDTO>> listResult = shortLinkRemoteService.listGroupShortLinkCount(groupDOList.stream().map(GroupDO::getGid).collect(Collectors.toList()));
        shortLinkGroupRespDTOS.forEach(each->{
            Optional<ShortLinkGroupCountQueryRespDTO> first = listResult.getData().stream()
                    .filter(rest -> rest.getGid()
                            .equals(each.getGid())).findFirst();
            first.ifPresent(item->each.setShortLinkCount(item.getShortLinkCount()));
        });
        return shortLinkGroupRespDTOS;

    }

    @Override
    public void updateGroup(ShortLinkGroupUpdateReqDTO requestParam) {
        LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, requestParam.getGid())
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = new GroupDO();
        groupDO.setName(requestParam.getName());
        baseMapper.update(groupDO, updateWrapper);
    }

    @Override
    public void deleteGroup(String gid) {
        LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = new GroupDO();
        groupDO.setDelFlag(1);
        baseMapper.update(groupDO, updateWrapper);
    }

    @Override
    public void sortGroup(List<ShortLinkGroupSortReqDTO> requestParam) {
        requestParam.forEach(each -> {

            LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                    .set(GroupDO::getSortOrder, each.getSortOrder())
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getGid, each.getGid())
                    .eq(GroupDO::getDelFlag, 0);
            baseMapper.update(null, updateWrapper);
        });
    }

    public boolean hasGid(String gid, String username){
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, username);
        GroupDO groupDO = baseMapper.selectOne(queryWrapper);

        if(Objects.isNull(groupDO)){
            return false;
        }
        return true;
    }
}
